package com.linkage.linkedlife.ui.activity

import android.app.TimePickerDialog
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import android.widget.TimePicker
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import cn.leancloud.AVException
import cn.leancloud.AVObject
import cn.leancloud.AVQuery
import cn.leancloud.livequery.AVLiveQuery
import cn.leancloud.livequery.AVLiveQueryEventHandler
import cn.leancloud.livequery.AVLiveQuerySubscribeCallback
import com.clark.dingding.model.Dingding
import com.linkage.linkedlife.R
import com.linkage.linkedlife.model.MessageEvent
import com.linkage.linkedlife.ui.service.MyService
import com.linkage.linkedlife.utils.AndroidUtils
import com.linkage.linkedlife.utils.SharedPreferencesUtil
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_main_ding.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.text.SimpleDateFormat
import java.util.*


class DingMainActivity : AppCompatActivity(), View.OnClickListener {

    private val formatter = SimpleDateFormat("HH:mm", Locale.getDefault())
    private var hour = 0
    private var minute = 0
    lateinit var serviceIntent: Intent

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main_ding)
        initView();
        EventBus.getDefault().register(this);
        serviceIntent = Intent(this, MyService::class.java)
    }

    private fun initView() {

        start_time.text = SharedPreferencesUtil.getString(this, "startTime", "08:30:00")
        end_time.text = SharedPreferencesUtil.getString(this, "endTime", "17:30:00")

        start_btn.setOnClickListener { v ->
            Log.d("clark", "clark")
            timePickerShow(start_time)
        }
        end_btn.setOnClickListener(View.OnClickListener {
            Log.d("clark", "end")
            timePickerShow(end_time)
        })
        ding_btn.setOnClickListener { v ->
            Log.d("clark", "checkdingding")
            if (AndroidUtils.isBackgroundRunning("com.alibaba.android.rimet", this)) {
                ding_state.text = "钉钉已运行"

            } else {
                ding_state.text = "钉钉未运行"
            }
        }

        start.setOnClickListener(this)
        end.setOnClickListener(this)

        val query = AVQuery<Dingding>("Todo")
        query.whereEqualTo("phone", "123456789");
        val liveQuery = AVLiveQuery.initWithQuery(query)
        liveQuery.setEventHandler(object : AVLiveQueryEventHandler() {
            override fun onObjectUpdated(newTodo: AVObject, updateKeys: List<String>) {
                Log.d("clark", "数据更新了") // 更新作品集
            }
        })
        liveQuery.subscribeInBackground(object : AVLiveQuerySubscribeCallback() {
            override fun done(e: AVException?) {
                if (e == null) {
                    // 订阅成功
                }
            }
        })

        ding_open_btn.setOnClickListener { v ->
            Log.d("clark", "open button click")

//            val todo = AVObject.createWithoutData("Dingding", "5fe42b899134d1505a30f5c3")
//            todo.put("state", System.currentTimeMillis())
//
//            // 将对象保存到云端
//            todo.saveInBackground().subscribe(object : io.reactivex.Observer<AVObject?> {
//                override fun onSubscribe(d: Disposable) {}
//                override fun onNext(todo: AVObject) {
//                    // 成功保存之后，执行其他逻辑
//                    println("保存成功。objectId：" + todo.objectId)
//                }
//
//                override  fun onError(e: Throwable) {
//                    // 异常处理
//                    e.printStackTrace()
//                }
//
//                override fun onComplete() {
//                    println("保存成功。objectId：" + todo.objectId)
//                }
//
//
//
//            })





            openRimet(this@DingMainActivity)
        }





    }


    override fun onClick(v: View?) {

        when (v?.id) {
            R.id.start -> {
                Log.d("clark", "start")
                startService(serviceIntent)
            }
            R.id.end -> {
                Log.d("clark", "end")
                stopService(serviceIntent)
            }
        }
    }

    fun timePickerShow(v: TextView) {
        var timePicker: TimePickerDialog =
            TimePickerDialog(
                this,
                { view: TimePicker?, hourOfDay: Int, minute: Int ->
                    onTimeSet(
                        hourOfDay,
                        minute,
                        v
                    )
                },
                hour,
                minute,
                true
            )
        timePicker.show()
    }

    private fun onTimeSet(newHour: Int, newMinute: Int, v: TextView): String {
        val cal = Calendar.getInstance()
        cal[Calendar.HOUR_OF_DAY] = newHour
        cal[Calendar.MINUTE] = newMinute
        cal.isLenient = false
        val format: String = formatter.format(cal.time) + ":00"
        when (v.id) {
            R.id.start_time -> {
                SharedPreferencesUtil.putString(this, "startTime", format)
                EventBus.getDefault().post(MessageEvent("startSet"))
            }
            R.id.end_time -> {
                SharedPreferencesUtil.putString(this, "endTime", format)
                EventBus.getDefault().post(MessageEvent("endSet"))
            }
        }
        v.setText(format)
        hour = newHour
        minute = newMinute
        return format
    }

    private fun openRimet(context: Context): Boolean {
        val packageManager = context.packageManager
        val pi: PackageInfo?
        val packageName = "com.alibaba.android.rimet"
        Log.d("clark","open rimet1")
        pi = try {
            packageManager.getPackageInfo(packageName, 0)
        } catch (e: PackageManager.NameNotFoundException) {
            //TODO 未安装钉钉
            return false
        }
        val resolveIntent = Intent(Intent.ACTION_MAIN, null)
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER)
        resolveIntent.setPackage(pi?.packageName)
        val apps =
            packageManager.queryIntentActivities(resolveIntent, 0)
        val resolveInfo = apps.iterator().next()
        if (resolveInfo != null) {
            Log.d("clark","open rimet2")
            val className = resolveInfo.activityInfo.name
            val intent = Intent(Intent.ACTION_VIEW)
            intent.addCategory(Intent.CATEGORY_LAUNCHER)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            val cn = ComponentName(packageName, className)
            intent.component = cn
            context.startActivity(intent)
            Log.d("clark","open rimet3")
            return true
        } else {
            //TODO resolveInfo = null
            Log.d("clark","open rimet4")
            return false
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(message: MessageEvent) {

        when (message.message) {
            "startOk" -> {
                Toast.makeText(this, "打开服务成功", Toast.LENGTH_SHORT).show()
            }
            "stopOk" -> {
                Toast.makeText(this, "关闭服务成功", Toast.LENGTH_SHORT).show()
                status.text = "--停止运行--"
            }
            "open" -> {
                ding_open_btn.performClick()
            }
            else  ->{
                status.text=message.message
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }


}